/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
var kthLargestLevelSum = function(root, k) {
    let queue = []
    let front = 0, rear = 0, levelPos = 0;
    queue.push(root)
    rear++
    levelPos++
    let sum = 0
    let arr = []
    while(front < levelPos) {
        let node = queue[front++]
        sum += node.val
        if(node.left) queue[rear++]
        if(node.right) queue[rear++]
        if(front == levelPos) {
            levelPos = rear
            arr.push(sum)
            sum = 0
        }
    }
    if(arr.length < k) return -1
    else {
        arr.sort((a, b) =>  a -b)
        return arr[k - 1]
    }
};